<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>角色管理</title>
    <!-- 引入 Vue.js -->
    <script src="/js/vue.js"></script>
    <!-- 引入 Element UI CSS -->
    <link type="text/css" rel="stylesheet" href="/css/index.css">
    <!-- 引入 Element UI JS -->
    <script src="/js/index.js"></script>
    <!-- 引入 Axios -->
    <script src="/js/axios.min.js"></script>
    <style>
        .app-container {
            padding: 20px;
            background-color: #f5f7fa;
            min-height: 100vh;
        }
        .search-container {
            margin-bottom: 20px;
            padding: 20px;
            background-color: #ffffff;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .table-container {
            padding: 20px;
            background-color: #ffffff;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .action-buttons {
            display: flex;
            gap: 8px;
            justify-content: center;
        }
        .pagination-container {
            margin-top: 20px;
            text-align: right;
        }
        .dialog-footer {
            text-align: right;
        }
        .status-normal {
            color: #67C23A;
            font-weight: bold;
        }
        .status-disabled {
            color: #F56C6C;
            font-weight: bold;
        }
        .del-flag-exist {
            color: #409EFF;
            font-weight: bold;
        }
        .del-flag-deleted {
            color: #F56C6C;
            font-weight: bold;
        }
    </style>
</head>
<body>
<div id="app" class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
        <el-row :gutter="15">
            <el-col :span="5">
                <el-input
                        size="small"
                        v-model="searchForm.roleName"
                        placeholder="请输入角色名称"
                        prefix-icon="el-icon-user"
                        clearable>
                </el-input>
            </el-col>
            <el-col :span="5">
                <el-select
                        size="small"
                        v-model="searchForm.status"
                        placeholder="请选择状态"
                        style="width: 100%;">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="正常" value="0"></el-option>
                    <el-option label="停用" value="1"></el-option>
                </el-select>
            </el-col>
            <el-col :span="14">
                <el-button
                        size="small"
                        type="primary"
                        icon="el-icon-search"
                        @click="search">
                    搜索
                </el-button>
                <el-button
                        size="small"
                        type="success"
                        icon="el-icon-plus"
                        @click="handleAdd">
                    添加
                </el-button>
                <el-button
                        size="small"
                        type="warning"
                        icon="el-icon-refresh"
                        @click="refreshData">
                    刷新
                </el-button>
            </el-col>
        </el-row>
    </div>

    <!-- 角色列表表格 -->
    <div class="table-container">
        <el-table
                :data="tableData"
                style="width: 100%"
                border
                stripe
                highlight-current-row>
            <el-table-column prop="roleName" label="角色名称" width="150" align="center"></el-table-column>
            <el-table-column prop="roleKey" label="角色权限字符" width="150" align="center"></el-table-column>

            <el-table-column prop="status" label="角色状态" width="100" align="center">
                <template slot-scope="scope">
                    <span :class="{
                        'status-normal': scope.row.status === '0',
                        'status-disabled': scope.row.status === '1'
                    }">
                        {{ statusMap[scope.row.status] }}
                    </span>
                </template>
            </el-table-column>

            <el-table-column prop="delFlag" label="删除标志" width="100" align="center">
                <template slot-scope="scope">
                    <span :class="{
                        'del-flag-exist': scope.row.delFlag === '0',
                        'del-flag-deleted': scope.row.delFlag === '1'
                    }">
                        {{ delFlagMap[scope.row.delFlag] }}
                    </span>
                </template>
            </el-table-column>

            <el-table-column prop="createBy" label="创建者" width="120" align="center"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
            <el-table-column prop="updateBy" label="更新者" width="120" align="center">
                <template slot-scope="scope">
                    {{ scope.row.updateBy || '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="180" align="center">
                <template slot-scope="scope">
                    {{ scope.row.updateTime || '-' }}
                </template>
            </el-table-column>
<!--            <el-table-column prop="updateBy" label="更新者" width="120" align="center"></el-table-column>-->
<!--            <el-table-column prop="updateTime" label="更新时间" width="180" align="center"></el-table-column>-->

            <el-table-column prop="remark" label="备注" min-width="180" align="center">
                <template slot-scope="scope">
                    <el-tooltip :content="scope.row.remark" placement="top" v-if="scope.row.remark">
                        <span class="remark-text">{{ scope.row.remark }}</span>
                    </el-tooltip>
                    <span v-else>-</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="280" align="center" fixed="right">
                <template slot-scope="scope">
                    <div class="action-buttons">
                        <el-button
                                size="mini"
                                type="success"
                                @click="handleRoleAuth(scope.row.roleId)"
                                icon="el-icon-setting">
                            角色授权
                        </el-button>
                        <el-button
                                size="mini"
                                type="primary"
                                @click="handleEdit(scope.$index, scope.row)"
                                icon="el-icon-edit">
                            编辑
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)"
                                icon="el-icon-delete">
                            删除
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    background>
            </el-pagination>
        </div>
    </div>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
            :title="title"
            :visible.sync="dialogFormVisible"
            width="500px"
            :close-on-click-modal="false">
        <el-form
                :model="form"
                :rules="rules"
                ref="form"
                label-width="120px"
                style="padding-right: 20px;">

            <el-form-item label="角色名称" prop="roleName">
                <el-input
                        v-model="form.roleName"
                        autocomplete="off"
                        placeholder="请输入角色名称">
                </el-input>
            </el-form-item>

            <el-form-item label="角色权限字符" prop="roleKey">
                <el-input
                        v-model="form.roleKey"
                        autocomplete="off"
                        placeholder="请输入角色权限字符">
                </el-input>
            </el-form-item>

            <!-- 状态字段：仅在编辑时显示 -->
            <el-form-item
                    label="角色状态"
                    prop="status"
                    v-if="title === '角色编辑'">
                <el-select
                        v-model="form.status"
                        placeholder="请选择状态"
                        style="width: 100%;">
                    <el-option label="正常" value="0"></el-option>
                    <el-option label="停用" value="1"></el-option>
                </el-select>
            </el-form-item>

            <!-- 删除标志字段：仅在编辑时显示 -->
            <el-form-item
                    label="删除标志"
                    prop="delFlag"
                    v-if="title === '角色编辑'">
                <el-select
                        v-model="form.delFlag"
                        placeholder="请选择删除标志"
                        style="width: 100%;">
                    <el-option label="存在" value="0"></el-option>
                    <el-option label="删除" value="1"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
                <el-input
                        type="textarea"
                        v-model="form.remark"
                        autocomplete="off"
                        placeholder="请输入备注"
                        :rows="3">
                </el-input>
            </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button @click="resetForm('form')">重置</el-button>
            <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 角色授权弹窗 -->
    <el-dialog
            :title="dialogTitle"
            :visible.sync="roleAuthDialogVisible"
            width="600px"
            :close-on-click-modal="false">
        <el-form :model="authForm" label-width="80px">
            <el-form-item label="权限分配">
                <el-tree
                        ref="menuTree"
                        :data="allMenus"
                        show-checkbox
                        node-key="id"
                        default-expand-all
                        :props="{ label: 'label', children: 'children' }"
                        :checked-keys="checkedMenuIds"
                        :check-strictly="true"
                        @check-change="handleCheckChange">
                </el-tree>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="roleAuthDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitRoleAuth">确 定</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                tableData: [],
                currentPage: 1,
                pageSize: 10,
                total: 0,
                searchForm: {},
                dialogFormVisible: false,
                title: '角色添加',
                form: {
                    roleName: '',
                    roleKey: '',
                    status: '',
                    delFlag: '',
                    remark: ''
                },
                formLabelWidth: '120px', //label的宽度 部门名称   部门位置
                originalForm: {},// 用于保存用户更新重置前的原始数据

                statusMap: {
                    '0': '正常',
                    '1': '停用'
                },
                delFlagMap: {
                    '0': '存在',
                    '1': '删除'
                },

                // 角色授权相关
                roleAuthDialogVisible: false,
                dialogTitle: '角色权限分配',
                allMenus: [], // 所有菜单树
                checkedMenuIds: [], // 当前角色已拥有的菜单ID
                currentRoleId: null,
                authForm: {},

                // ...
                dateFormat: 'YYYY-MM-DD HH:mm:ss', // 定义格式
                rules: {
                    roleName: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' },
                        {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
                    ],
                    roleKey: [
                        { required: true, message: '请输入角色权限字符', trigger: 'blur' },
                        {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
                    ],
                    status: [
                        { required: true, message: '请选择角色状态', trigger: 'change' }
                    ],
                    delFlag: [
                        { required: true, message: '请选择删除标志', trigger: 'change' }
                    ]
                },

            };
        },
        created() {
            this.loadData();
        },
        methods: {
            loadData() {
                let _this = this;
                axios.post('/role/queryByPage', {
                    pageNo: this.currentPage,
                    pageSize: this.pageSize,
                    data: this.searchForm
                }).then(function (response) {
                    console.log("hhhhhhh============"+response.data) // 打印完整响应
                    if (response.data.code === 200) {
                        _this.tableData = response.data.data.list;
                        _this.total = response.data.data.total;
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },

            handleSizeChange(val) {
                this.pageSize = val;
                this.loadData();
            },

            handleCurrentChange(val) {
                this.currentPage = val;
                this.loadData();
            },

            search() {
                this.loadData();
            },

            refreshData() {
                this.searchForm = {};
                this.loadData();
            },

            handleAdd() {
                this.dialogFormVisible = true;
                this.title = '角色添加';
                this.form = {
                    roleName: '',
                    roleKey: '',
                    status: '',
                    delFlag: '',
                    remark: ''
                };
                // 清除验证状态
                this.resetForm('form');
            },

            handleEdit(index, row) {
                this.dialogFormVisible = true;
                this.title = '角色编辑';
                this.originalForm = JSON.parse(JSON.stringify(row));
                this.form = JSON.parse(JSON.stringify(row));
                // 清除验证状态
                this.resetForm('form');
            },

            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let uri = '/role/add';
                        if (this.title === '角色编辑') {
                            uri = '/role/edit';
                        }
                        let _this = this;
                        axios.post(uri, this.form)
                            .then(function (response) {
                                if (response.data.code === 200) {
                                    _this.$message.success('操作成功');
                                    _this.loadData();
                                    _this.dialogFormVisible = false;
                                } else {
                                    _this.$message.error('操作失败');
                                }
                            }).catch(function (error) {
                            console.log(error);
                        });
                    }
                });
            },

            resetForm(formName) {
                if (this.title === '角色编辑') {
                    this.form = JSON.parse(JSON.stringify(this.originalForm));
                    this.$nextTick(() => {
                        this.$refs[formName].clearValidate();
                    });
                } else {
                    this.form = {
                        roleName: '',
                        roleKey: '',
                        status: '',
                        delFlag: '',
                        remark: ''
                    };
                    this.$refs[formName].resetFields();
                }
            },

            handleDelete(index, row) {
                this.$confirm('此操作将永久删除该角色，是否继续？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let _this = this;
                    axios.delete('/role/deleteById?roleId=' + row.roleId)
                        .then(function (response) {
                            if (response.data.code === 200) {
                                _this.$message.success('删除成功');
                                _this.loadData();
                            } else {
                                _this.$message.error(response.data.message || '删除失败');
                            }
                        }).catch(function (error) {
                        console.log(error);
                    });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            },

            // 角色授权
            handleRoleAuth(roleId) {
                this.currentRoleId = roleId;
                this.checkedMenuIds = []; // 清空旧权限

                this.roleAuthDialogVisible = true;

                this.$nextTick(() => {
                    this.$refs.menuTree.setCheckedKeys([]); // 清除树勾选
                    this.loadAllMenus();
                    this.loadRoleMenus(roleId);
                });
            },

            // 加载所有菜单树
            loadAllMenus() {
                let _this = this;
                axios.get('/role/menus/all')
                    .then(function (response) {
                        console.log('=== 获取所有菜单响应 ===');
                        console.log(response); // 查看完整响应
                        if (response.data.code === 200) {
                            _this.allMenus = response.data.data;
                            console.log('allMenus:', _this.allMenus);
                            // 添加调试信息，检查节点结构
                            if (_this.allMenus && _this.allMenus.length > 0) {
                                console.log('第一个节点结构:', _this.allMenus[0]);
                            }
                        } else {
                            console.error('获取菜单失败:', response.data.msg);
                        }
                    })
                    .catch(function (error) {
                        console.error('请求失败:', error);
                    });
            },

            // 加载当前角色已分配的菜单
            loadRoleMenus(roleId) {
                let _this = this;
                axios.get(`/role/menus/${roleId}`)
                    .then(function (response) {
                        if (response.data.code === 200) {
                            const menus = response.data.data;
                            _this.checkedMenuIds = menus.map(menu => menu.menuId);
                            console.log('角色拥有的菜单ID:', _this.checkedMenuIds);

                            _this.$nextTick(() => {
                                _this.$refs.menuTree.setCheckedKeys(_this.checkedMenuIds);
                            });
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },

            // 处理树节点勾选变化
            handleCheckChange(data, checked, indeterminate) {
                // 可选：实时更新 selectedMenuIds
                // 这里可以用于后续提交
            },

            // 提交权限分配
            submitRoleAuth() {
                let _this = this;
                const checkedNodes = this.$refs.menuTree.getCheckedNodes();
                const halfCheckedNodes = this.$refs.menuTree.getHalfCheckedNodes();
                // const allCheckedIds = [...checkedNodes.map(node => node.menuId), ...halfCheckedNodes.map(node => node.menuId)];
                // 添加调试信息
                console.log('选中的节点:', checkedNodes);
                console.log('半选中的节点:', halfCheckedNodes);

                // 过滤并提取有效的menuId
                const checkedMenuIds = checkedNodes
                    .map(node => node.id)
                    .filter(id => id !== undefined && id !== null);

                const halfCheckedMenuIds = halfCheckedNodes
                    .map(node => node.id)
                    .filter(id => id !== undefined && id !== null);

                const allCheckedIds = [...checkedMenuIds, ...halfCheckedMenuIds];

                // 添加调试信息
                console.log('提取的menuIds:', allCheckedIds);

                // 如果没有选中任何菜单，也要发送空数组而不是undefined
                const finalMenuIds = allCheckedIds.length > 0 ? allCheckedIds : [];

                console.log('最终发送的menuIds:', finalMenuIds);



                axios.post('/role/assignMenus', {
                    roleId: this.currentRoleId,
                    menuIds: allCheckedIds
                })
                    .then(function (response) {
                        if (response.data.code === 200) {
                            _this.$message.success('权限分配成功');
                            _this.roleAuthDialogVisible = false;
                            _this.loadData(); // 刷新角色列表
                        } else {
                            _this.$message.error('权限分配失败');
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        _this.$message.error('网络错误');
                    });
            }

        }
    });
</script>
</body>
</html>
